package com.yeskery.nut.cloud.registry.redis;

import com.yeskery.nut.annotation.bean.Bean;
import com.yeskery.nut.annotation.bean.Configuration;
import com.yeskery.nut.annotation.condition.ConditionalOnMissingBean;
import com.yeskery.nut.annotation.condition.ConditionalOnWebApplicationType;
import com.yeskery.nut.core.Environment;
import com.yeskery.nut.extend.redis.JedisConnectionPool;
import com.yeskery.nut.extend.redis.JedisPlugin;

import java.util.Optional;

/**
 * redis服务注册注册器
 * @author YESKERY
 * 2024/1/12
 */
@Configuration
public class RedisServerRegistryRegistrar {

    /**
     * 配置redis服务注册bean
     * @return redis服务注册bean
     */
    @Bean
    @ConditionalOnWebApplicationType
    public RedisServerRegistry redisServerRegistry() {
        return new RedisServerRegistry();
    }

    /**
     * 配置jedis插件
     * @param environment 环境对象
     * @return jedis插件
     */
    @Bean
    @ConditionalOnMissingBean({JedisConnectionPool.class, JedisPlugin.class})
    @ConditionalOnWebApplicationType
    public JedisPlugin redisServerJedisPlugin(Environment environment) {
        String host = Optional.ofNullable(environment.getEnvProperty("nut.cloud.redis.host")).orElse("127.0.0.1");
        Integer port = Optional.ofNullable(environment.getEnvProperty("nut.cloud.redis.port")).map(Integer::valueOf).orElse(6379);
        String password = environment.getEnvProperty("nut.cloud.redis.password");
        Integer database = Optional.ofNullable(environment.getEnvProperty("nut.cloud.redis.database")).map(Integer::valueOf).orElse(0);
        return new JedisPlugin(host, port, password, database);
    }
}
